import {
  PieChartOutlined,
  DesktopOutlined,
  UserOutlined,
  TeamOutlined,
  FileOutlined,
} from '@ant-design/icons'
import { Menu, MenuProps } from 'antd'
import { useNavigate, useLocation } from 'react-router-dom'
import { useState } from 'react'
import MenuItem from 'antd/es/menu/MenuItem'

type MenuItem = Required<MenuProps>['items'][number] & {
  children?: MenuItem[]
  label: React.ReactNode
}

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[]
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem
}
const items: MenuItem[] = [
  getItem('栏目 1', '/page1', <PieChartOutlined />),
  getItem('栏目 2', '/page2', <DesktopOutlined />),
  getItem('栏目 3', '/page3', <UserOutlined />, [
    getItem('栏目 301', '/page3/page301'),
    getItem('栏目 302', '/page3/page302'),
    getItem('栏目 303', '/page3/page303'),
  ]),
  getItem('栏目 4', '/page4', <TeamOutlined />, [
    getItem('栏目 401', '/page4/page401'),
    getItem('栏目 402', '/page4/page402'),
  ]),
  getItem('栏目 5', '/page5', <FileOutlined />),
]

const Comp: React.FC = () => {
  const navigateTo = useNavigate()

  const currentRoute = useLocation()

  const menuClick = (e: { key: string }) => {
    // 点击跳转到响应的路由 编程式路由导航
    navigateTo(e.key)
  }
  let firstOpenKey: string = ''
  for (let i = 0; i < items.length; i++) {
    if (
      items[i]!.children &&
      items[i]!.children!.length > 0 &&
      !!items[i]!.children!.find(
        (item: MenuItem) => item!.key === currentRoute.pathname
      )
    ) {
      firstOpenKey = items[i]!.key as string
      break
    }
  }
  const [openKeys, setOpenKeys] = useState([firstOpenKey])
  const handleOpenChange = (openKeys: string[]) => {
    setOpenKeys([openKeys[openKeys.length - 1]])
  }
  return (
    <Menu
      theme="dark"
      defaultSelectedKeys={[currentRoute.pathname]}
      mode="inline"
      items={items}
      onClick={menuClick}
      onOpenChange={handleOpenChange}
      openKeys={openKeys}
    />
  )
}
export default Comp
